//
//  DetailsHotelFacilitiesController.swift
//  AirTravel
//
//  Created by apple on 2021/7/22.
//

import UIKit
import WebKit

class DetailsHotelFacilitiesController: UIViewController {
    
    @IBOutlet weak var tabView: UITableView!
    @IBOutlet weak var entertainmentView: UIView!
    /// 娱乐
    @IBOutlet weak var entertainmentBtn: UIButton!
    @IBOutlet weak var facilitiesView: UIView!
    /// 设施
    @IBOutlet weak var facilitiesBtn: UIButton!
    @IBOutlet weak var policyView: UIView!
    /// 政策
    @IBOutlet weak var policyBtn: UIButton!
    @IBOutlet weak var recommendedView: UIView!
    /// 推荐理由
    @IBOutlet weak var recommendedBtn: UIButton!
    var webView = WKWebView()
    let identifyHH = "HotelHeaderView"
    let identifyHP = "HotelPhoneCell"
    let identifyXB = "XnBannerCell"
    let identifyCP = "CurrentPoliticsCell"
    let identifyXHF = "XnHotelFacilitiesCell"
    
    
    var height : CGFloat = 0.0
    var currentSection = 0
    var isUpScroll = false
    var isFirstLoad = true
    var oldY : CGFloat = 0.0
    
    var hotelDetail:CityHotelMianModel?
    
    var hotelArr:[String] = []
    
    //视图将要显示
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        addObservers()
    }
    
    //视图将要消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        removeObservers()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "详情/设施"
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.estimatedRowHeight = 120
        self.tabView.rowHeight = UITableView.automaticDimension
        self.tabView.register(UINib.init(nibName: "HotelHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: identifyHH)
        self.tabView.register(UINib.init(nibName: "HotelPhoneCell", bundle: nil), forCellReuseIdentifier: identifyHP)
        self.tabView.register(UINib.init(nibName: "XnBannerCell", bundle: nil), forCellReuseIdentifier: identifyXB)
        self.tabView.register(UINib.init(nibName: "CurrentPoliticsCell", bundle: nil), forCellReuseIdentifier: identifyCP)
        self.tabView.register(UINib.init(nibName: "XnHotelFacilitiesCell", bundle: nil), forCellReuseIdentifier: identifyXHF)
        
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 120))
        webView.navigationDelegate = self
             
        webView.scrollView.isScrollEnabled = true
        webView.load(URLRequest(url: URL(string: "https://mbd.baidu.com/newspage/data/landingsuper?context=%7B%22nid%22%3A%22news_10368690556170977958%22%7D&n_type=0&p_from=1")!))
        
        
        let arraySubstrings: [Substring] = (hotelDetail?.serviceName.split(separator: ","))!
        
        var arrayStrings: [String] = []
        for item in arraySubstrings {
                    
            arrayStrings.append("\(item)")
           
        }
        
        self.hotelArr = arrayStrings
        
        self.policyBtn.addTarget(self, action: #selector(topClick(sender:)), for: .touchUpInside)
        self.facilitiesBtn.addTarget(self, action: #selector(topClick(sender:)), for: .touchUpInside)
        self.entertainmentBtn.addTarget(self, action: #selector(topClick(sender:)), for: .touchUpInside)
        self.recommendedBtn.addTarget(self, action: #selector(topClick(sender:)), for: .touchUpInside)
    }
    
    @objc func topClick(sender:UIButton) {
        self.currentSection = sender.tag
        self.tabView.scrollToRow(at: IndexPath(item: 0, section: sender.tag), at: UITableView.ScrollPosition.top, animated: false)
        self.refreshHead()
        
    }

    func addObservers() {
        self.webView.addObserver(self, forKeyPath: "scrollView.contentSize", options: .new, context: nil)
    }
    
    func removeObservers() {
        self.webView.removeObserver(self, forKeyPath: "scrollView.contentSize")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "scrollView.contentSize" {
            let height = self.webView.scrollView.contentSize.height
            if height <= 0 {
                return
            }
            self.webView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: height)
            self.height = height
        }
    }
}

extension DetailsHotelFacilitiesController:UITableViewDataSource,UITableViewDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 2:
            return hotelDetail?.policy?.count ?? 0
            
        case 3:
            return hotelArr.count
        default:
            return 1
        }
    }
    
    @objc func phoneClick(){
        
        
        UIApplication.shared.canOpenURL(URL(string: "\(hotelDetail?.mobile ?? "")")!)
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyHP) as! HotelPhoneCell
            cell.yearsLab.text = "\(hotelDetail?.bulitTime.substring(to: 3) ?? "")年装修"
            
            cell.phoneLab.text = "酒店电话: \(hotelDetail?.mobile ?? "")"
            
            cell.phoneBtn.addTarget(self, action: #selector(phoneClick), for: .touchUpInside)
            cell.selectionStyle = .none
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyXB) as! XnBannerCell
            cell.selectionStyle = .none
            cell.backView.addSubview(self.webView)
            return cell
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyCP) as! CurrentPoliticsCell
            cell.contenLab.text = hotelDetail?.policy?[indexPath.row].policyText
            cell.selectionStyle = .none
            cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0);
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: identifyXHF) as! XnHotelFacilitiesCell
            cell.titleLab.text = hotelArr[indexPath.row]
            cell.contentLab.text = ""
            cell.selectionStyle = .none
            cell.separatorInset = UIEdgeInsets(top: 0, left: SCREEN_WIDTH, bottom: 0, right: 0);
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        switch indexPath.section {
        case 1:
            return self.height
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 8
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = tableView.dequeueReusableHeaderFooterView(withIdentifier: identifyHH) as! HotelHeaderView
        switch section {
        case 0:
            headView.titleLab.text = hotelDetail?.hotelName
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        case 1:
            headView.titleLab.text = "图文详情"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        case 2:
            headView.titleLab.text = "酒店政策"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        case 3:
            headView.titleLab.text = "酒店设施"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        case 4:
            headView.titleLab.text = "交通娱乐"
            headView.img.isHidden = true
            headView.leftLine.constant = 18
        default:
            headView.img.isHidden = true
            headView.titleLab.isHidden = true
        }
        return headView
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        let footerView = UIView.init()
        footerView.backgroundColor = UIColor.groupTableViewBackground
        return footerView
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        if self.isUpScroll == false  {
            //最上面组头（不一定是第一个组头，指最近刚被顶出去的组头）又被拉回来
            if section == 0 || section == 1 {
                self.currentSection = 0
            }else{
                self.currentSection = section
            }
            self.refreshHead()
            print("willDisplayHeaderView显示第\(section)组")
        }
    }
    
    func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int){
        if self.isFirstLoad == false && self.isUpScroll {
            if section + 1 == 0 || section + 1 == 1 {
                self.currentSection = 0
            }else{
                self.currentSection = section + 1
            }
            self.refreshHead()
            print("didEndDisplayingHeaderView显示第\(section + 1)组")
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.tabView.contentOffset.y > self.oldY {
            //上滑
            self.isUpScroll = true
        }else{
            //下滑
            self.isUpScroll = false
        }
        self.isFirstLoad = false
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //获取开始拖拽tab的偏移量
        self.oldY = self.tabView.contentOffset.y
    }
    //刷新头部
    func refreshHead() {
        self.recommendedBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        self.recommendedView.isHidden = true
        self.policyBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        self.policyView.isHidden = true
        self.facilitiesBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        self.facilitiesView.isHidden = true
        self.entertainmentBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        self.entertainmentView.isHidden = true
        switch self.currentSection {
        case 0:
            self.recommendedBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            self.recommendedView.isHidden = false
        case 2:
            self.policyBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            self.policyView.isHidden = false
        case 3:
            self.facilitiesBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            self.facilitiesView.isHidden = false
        case 4:
            self.entertainmentBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            self.entertainmentView.isHidden = false
        default:
            break
        }
    }
}

extension DetailsHotelFacilitiesController:WKNavigationDelegate{
    // 页面开始加载时调用
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
//        self.navigationItem.title = "加载中..."
        
    }
    // 当内容开始返回时调用
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
    }
    // 页面加载完成之后调用
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        /// 获取网页title
//        self.title = self.webView.title
        webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'", completionHandler: nil)
        self.tabView.reloadData()
    }
    // 页面加载失败时调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        
        /// 弹出提示框点击确定返回
        let alertView = UIAlertController.init(title: "提示", message: "加载失败", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title:"确定", style: .default) { okAction in
            _=self.navigationController?.popViewController(animated: true)
        }
        alertView.addAction(okAction)
        self.present(alertView, animated: true, completion: nil)
        
    }
}
